package pe.edu.upc.dsd.clienteweb.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import pe.edu.upc.dsd.agencianavierawssoap.service.EmbarqueService;
import pe.edu.upc.dsd.clienteweb.form.FormFactura;
import pe.edu.upc.dsd.clienteweb.jms.MessageProducer;

import pe.edu.upc.dsd.clienteweb.model.Factura;

@Controller
@RequestMapping("/facturacion")
public class FacturacionController {

	private Logger logger = Logger.getLogger(FacturacionController.class);

	@Autowired
	private EmbarqueService embarqueService; // Asociar el webservice
	
	@Autowired
    private MessageProducer messageProducer;

	@RequestMapping(method = RequestMethod.GET)
	public String initForm(ModelMap model) {

		logger.debug("Ingresando al formulario facturacion ");

		FormFactura formFactura = new FormFactura();

		// command object
		model.addAttribute("formFactura", formFactura);

		// return form view
		return "facturacion";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(@ModelAttribute("formFactura") FormFactura formFactura,
			BindingResult result, SessionStatus status, Model model) {

		// clear the command object from the session
		//status.setComplete();
		
		messageProducer.send("Factura n 1" + formFactura.getCodigo());

		logger.debug("Factura: " + formFactura.getCodigo());

		Factura factura = embarqueService.obtenerFactura(formFactura.getCodigo());

		// logger.debug(respuesta.getMensaje());

		model.addAttribute("factura",factura);
		logger.debug("Enviando el pago: " + factura.getCodigoEmbarque());
		messageProducer.send(factura.getCodigoEmbarque()+" "+
							factura.getFecha()+" "+
							factura.getMonto());


		// return form success view
		return "facturacionConfirmacion";
		
	}
	
	
}
